import jwt
from datetime import datetime, timedelta
from django.conf import settings
from functools import wraps


def login_exempt(view_func):
	"""登录豁免,被此装饰器修饰的action可以不校验登录."""
	
	def wrapped_view(*args, **kwargs):
		return view_func(*args, **kwargs)
	
	wrapped_view.login_exempt = True
	return wraps(view_func)(wrapped_view)


class Token(object):
	
	def __init__(self, jwt_key=None, alg='HS256'):
		self.jwt_key = jwt_key if jwt_key else settings.JWT_KEY
		self.alg = alg
	
	def create_token(self, username, timeout=20):
		# 声明类型，声明加密算法
		headers = {
			"type": "jwt",
			"alg": self.alg
		}
		payload = dict(
			username=username,
			exp=datetime.now() + timedelta(minutes=timeout)  # 过期时间
		)
		token = jwt.encode(payload=payload, key=self.jwt_key, algorithm=self.alg, headers=headers)
		return token
	
	def verify_token(self, token):
		res = {'msg': '验证成功', 'code': 200, 'data': None}
		status = False
		try:
			res['data'] = jwt.decode(jwt=token, key=self.jwt_key, algorithms=self.alg, verify=True)
			status = True
		except jwt.ExpiredSignatureError:
			res = {'msg': 'token已失效', 'code': 300, 'data': None}
		except jwt.DecodeError:
			res = {'msg': 'token认证失败', 'code': 301, 'data': None}
		except jwt.InvalidTokenError:
			res = {'msg': '非法的token', 'code': 302, 'data': None}
		return status, res
